<template>
  <div>
    <!-- 面包导航 -->
    <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
      <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-form :inline="true">
      <el-form-item>
        <el-input v-model="searchForm.name" placeholder="请输入用户名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="medium" type="primary" icon="el-icon-search" @click="getUserList">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button size="medium" type="primary" icon="el-icon-plus" @click="dialogFormVisible = true" v-if="hasAuth('sys:user:save')">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-popconfirm
            title="确定要批量删除用户吗？"
            icon="el-icon-info"
            icon-color="red"
            @confirm="delBatchHandle"
        >
          <el-button size="medium" type="danger" icon="el-icon-delete" slot="reference" :disabled="delBtnStatus" v-if="hasAuth('sys:user:delete')">批量删除
          </el-button>
        </el-popconfirm>
      </el-form-item>
    </el-form>

    <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        border
        stripe
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          label="头像"
          width="50">
        <template slot-scope="scope">
          <el-avatar size="small" :src="scope.row.avatar"></el-avatar>
        </template>
      </el-table-column>

      <el-table-column
          prop="username"
          label="用户名"
          width="120">
      </el-table-column>

      <el-table-column
          prop="code"
          label="角色名称">
        <template slot-scope="scope">
          <el-tag size="small" v-for="item in scope.row.sysRoles">{{ item.name }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column
          prop="email"
          label="邮箱">
      </el-table-column>

<!--      <el-table-column-->
<!--          prop="phone"-->
<!--          label="手机号">-->
<!--      </el-table-column>-->

      <el-table-column
          prop="status"
          label="状态"
          width="70">
        <template slot-scope="scope">
          <el-tag size="small" type="success" v-if="scope.row.status === 1">正常</el-tag>
          <el-tag size="small" type="danger" v-else-if="scope.row.status === 0">禁用</el-tag>
        </template>
      </el-table-column>

      <el-table-column
          prop="created"
          width="180"
          label="创建时间"
      >
      </el-table-column>

      <el-table-column
          label="操作"
          width="360">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="roleHandle(scope.row.id)" v-if="hasAuth('sys:user:role')">分配角色</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button size="mini" type="primary" @click="repassHandle(scope.row.id, scope.row.username)" v-if="hasAuth('sys:user:repass')">重置密码</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button size="mini" type="primary" @click="editHandle(scope.row.id)" v-if="hasAuth('sys:user:update')">编辑</el-button>
          <el-divider direction="vertical"></el-divider>
          <template>
            <el-popconfirm
                title="确定要删除该用户吗？"
                icon="el-icon-info"
                icon-color="red"
                @confirm="delHandle(scope.row.id)"
            >
              <el-button size="mini" type="danger" slot="reference" v-if="hasAuth('sys:user:delete')">删除</el-button>
            </el-popconfirm>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100]"
        :current-page="current"
        :page-size="size"
        :total="total">
    </el-pagination>

    <!--  新增对话框  -->
    <el-dialog title="新增用户" :visible.sync="dialogFormVisible" width="600px" :before-close="handleClose">
      <el-form :model="editForm" :rules="editFormRules" ref="editForm">
        <el-form-item label="用户名" prop="username" label-width="100px">
          <el-input v-model="editForm.username" autocomplete="off"></el-input>
          <el-alert
              title="初始密码为123456"
              :closable="false"
              type="info"
              style="line-height: 12px;"
          ></el-alert>
        </el-form-item>

        <el-form-item label="邮箱" prop="email" label-width="100px">
          <el-input v-model="editForm.email" autocomplete="off"></el-input>
        </el-form-item>

<!--        <el-form-item label="手机号" prop="phone" label-width="100px">-->
<!--          <el-input v-model="editForm.phone" autocomplete="off"></el-input>-->
<!--        </el-form-item>-->

        <el-form-item label="状态" prop="status" label-width="100px">
          <el-radio-group v-model="editForm.status">
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="1">正常</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('editForm')">提交</el-button>
        <el-button @click="reset('editForm')">重置</el-button>
      </div>
    </el-dialog>

    <!--  分配角色对话框  -->
    <el-dialog title="分配角色" :visible.sync="dialogRoleVisible" width="600px">
      <el-form :model="roleForm">
        <el-tree
            :data="roleTreeData"
            show-checkbox
            ref="roleTree"
            :default-expand-all="true"
            node-key="id"
            check-strictly
            :props="defaultProps">
        </el-tree>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRoleForm('roleForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "User",
  data() {
    return {
      searchForm: {},
      delBtnStatus: true,
      total: 0,
      current: 1,
      size: 10,
      dialogRoleVisible: false,
      dialogFormVisible: false,
      editForm: {}, //编辑用户
      roleForm: {}, //分配角色对话框
      editFormRules: {
        username: [
          {required: true, message: '请输入用户名称', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          { type: 'email', message: '邮箱格式不正确'}
        ],
        status: [
          {required: true, message: '请选择状态', trigger: 'blur'}
        ]
      },
      tableData: [],
      multipleSelection: [], //选中的对象
      roleTreeData: [], //角色树形数据
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created() {
    this.getUserList()
    request.get('/sys/role/list').then(res => {
      this.roleTreeData = res.data.records
    })
  },
  methods: {
    //重置密码
    repassHandle(id, username) {
      this.$confirm('将重置用户【' + username + '】的密码, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request.post("/sys/user/repass", id).then(res => {
          this.$message({
            showClose: true,
            message: '恭喜你，重置密码成功',
            type: 'success',
            onClose: () => {
            }
          });
        })
      })
    },
    //提交用户角色信息
    submitRoleForm(formName) {
      //获取被选中的菜单id
      let roleIds = this.$refs.roleTree.getCheckedKeys()
      request.post('/sys/user/perm/' + this.roleForm.id, roleIds).then(res => {
        this.$message({
          showClose: true,
          message: '恭喜你，分配角色成功',
          type: 'success',
          onClose: () => {
            this.getUserList()
          }
        })
        this.dialogRoleVisible = false
      })
    },
    //获取当前角色
    roleHandle(id) {
      this.dialogRoleVisible = true
      request.get('/sys/user/info/' + id).then(res => {
        //角色默认赋值
        let roleIds = res.data.sysRoles.map(r => r.id)
        this.$refs.roleTree.setCheckedKeys(roleIds)
        this.roleForm = res.data
      })
    },
    //关闭对话框，清空数据
    handleClose() {
      this.resetForm('editForm')
    },
    //获取角色列表
    getUserList() {
      request.get("/sys/user/list", {
        params: {
          username: this.searchForm.username,
          current: this.current,
          size: this.size
        }
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
        this.size = res.data.size
        this.current = res.data.current
      })
    },
    //删除用户
    delHandle(id) {

      request.post("/sys/user/delete/" + id).then(res => {
        this.$message({
          showClose: true,
          message: '恭喜你，删除用户成功',
          type: 'success',
          onClose: () => {
            this.getUserList()
          }
        });
      })
    },
    //获取编辑用户
    editHandle(id) {
      request.get("/sys/user/info/" + id).then(res => {
        //数据回显
        this.editForm = res.data
        //打开对话框
        this.dialogFormVisible = true
      })
    },
    //提交表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 有id就是修改，否则就是新增
          request.post('/sys/user/' + (this.editForm.id ? "update" : "save"), this.editForm)
              .then(res => {
                this.resetForm(formName)
                //提示信息
                this.$message({
                  showClose: true,
                  message: '恭喜你，编辑用户成功',
                  type: 'success',
                  //关闭这条消息时更新数据
                  onClose: () => {
                    this.getUserList()
                  }
                });
                //关闭对话框
                this.resetForm('editForm')
                this.dialogFormVisible = false
              })
        } else {
          console.log('提交出错!!');
          return false;
        }
      });
    },
    //重置数据
    reset(formName) {
      this.$refs[formName].resetFields()
      this.editForm = {}
    },
    //清空数据
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.editForm = {}
      this.dialogFormVisible = false
    },
    handleSizeChange(val) {
      this.size = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      this.current = val
      this.getUserList()
    },
    //多选
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    //选中的目标
    handleSelectionChange(val) {
      this.multipleSelection = val;

      this.delBtnStatus = val.length <= 0;
    },
    //批量删除
    delBatchHandle() {
      let ids = this.multipleSelection.map(user => user.id)
      request.post("/sys/user/deleteBatch", ids).then(res => {
        this.$message({
          showClose: true,
          message: '恭喜你，批量删除用户成功',
          type: 'success',
          onClose: () => {
            this.getUserList()
          }
        });
      })
    }
  }
}
</script>

<style scoped>
.el-pagination {
  float: right;
  margin-top: 22px;
}
</style>